package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Tu
 * @date 2023/4/12 17:19
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    /**
     * 原子类
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 模拟自旋锁获取服务
     * JUC并发
     *
     * @return
     */
    public final int getInstance() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            //2147483647  Integer.MAX_VALUE  整型的最大值
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("第几次，获取服务next：" + next);
        return next;
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        //模拟源码轮询取服务
        int index = getInstance() % serviceInstances.size();
        System.out.println("最终获取服务下标" + index);
        return serviceInstances.get(index);
    }

}
